Imports System
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization

Public Class BoardProgramming_New
    Private m_upload As Boolean
    Private m_ptRow As DataRow
    Private m_newcar As BikiSoft.CarBase
    Private m_mapOne As Byte()
    Private m_mapTwo As Byte()
    Private m_mapThree As Byte()
    Private m_temp As Byte()

    Private Enum Test_Number As Byte
        Board_Program
        Test_Pattern
        Flash_Test
        Consult_Loopback
        Consult_LoopBackClk
        Load_BaseData
    End Enum

    Private m_CurrentTest As Test_Number = Test_Number.Board_Program

    Public Sub arrayDump(ByRef sArray() As Byte, ByVal sOutFile As String)
        Dim fStream As New FileStream(sOutFile, FileMode.Create)
        'Dim bWrite As New (fStream)
        fStream.Write(sArray, 0, sArray.Length)
        fStream.Close()
    End Sub

    Private Sub bwg_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bwg.DoWork
        Dim em As Program = CType(e.Argument, Program)
        AddHandler em.Message, AddressOf EventProgress
        AddHandler em.Progress, AddressOf EventProgress

        em.Execute(bwg, e)
    End Sub
    Private Sub EventProgress( _
       ByVal sender As Object, ByVal e As Emergency_Args)

        Dim intPercent As Integer = e.Progress
        If intPercent >= 100 Then
            intPercent = 100
        ElseIf intPercent < 0 Then
            intPercent = 0
        End If
        bwg.ReportProgress(intPercent, e)
    End Sub
    Private Sub bwg_ProgressChanges( _
        ByVal sender As Object, _
        ByVal e As System.ComponentModel.ProgressChangedEventArgs) _
        Handles bwg.ProgressChanged

        Dim state As Emergency_Args = CType(e.UserState, Emergency_Args)
        Me.setBar(state.Progress)
        Err_message(state.Message)
    End Sub
    Private Sub bwg_RunWorkerCompleted( _
        ByVal sender As Object, _
        ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) _
        Handles bwg.RunWorkerCompleted
        m_upload = False
    End Sub

    Private Sub BoardProgramming_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Me.odbcCodesAdapter.Fill(DataSet1)
        cbSpeed.SelectedIndex = 0

    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdProgram.Click
        Dim f_found As Boolean = False
        m_ptRow = Nothing
        Dim f As BK_SPEEDS
        Dim f_eepromData As String = Application.StartupPath + "\data\eeprom.bin"
        Dim f_firmware As String = Application.StartupPath & "\data\"
        Dim f_bootloader As String = Application.StartupPath & "\data\"

        Select Case cbSpeed.SelectedIndex
            Case 0
                f = BK_SPEEDS.BK_8MHz
                f_firmware &= "BIKI_OS_1.0.8.bin"
                f_bootloader &= "BIKIBOOT_V1.0_8.bin"
            Case 1
                f = BK_SPEEDS.BK_12MHz
                f_firmware &= "BIKI_OS_1.0.12.bin"
                f_bootloader &= "BIKIBOOT_V1.0_12.bin"
            Case 2
                f = BK_SPEEDS.BK_16MHz
                f_firmware &= "BIKI_OS_1.0.16.bin"
                f_bootloader &= "BIKIBOOT_V1.0_16.bin"
            Case Else
                MsgBox("Invalid speed selected")
                Exit Sub
        End Select

        Dim f_firm() As Byte = arrayLoad(f_firmware)
        Dim f_boot() As Byte = arrayLoad(f_bootloader)
        Dim f_EEprom() As Byte = arrayLoad(f_eepromData)

        If IsNothing(f_firm) Or IsNothing(f_boot) Or IsNothing(f_EEprom) Then
            MsgBox("Files Missing")
            Exit Sub
        End If

        If Not Trim(txNumber.Text) = "" And Val(txNumber.Text) >= 1 Then
            For Each dCurrent As DataRow In DataSet1.Tables("Codes").Rows
                If dCurrent.Item("SerialNo") = Val(txNumber.Text) Then
                    f_found = True
                    ' Found Matching number!
                    Dim f_BLoffset As Integer
                    Dim f_EEoffset As Integer
                    Dim f_count As Integer
                    Dim f_code() As Byte
                    f_BLoffset = 3952
                    f_EEoffset = 136
                    For i As Integer = 1 To 8
                        f_code = cv_BytesFromHex(CType(dCurrent.Item("Security Code" & Str(i)), String))
                        f_count = 0
                        For Each bit As Byte In f_code
                            'f_boot(f_BLoffset + f_count) = bit
                            f_EEprom(f_EEoffset - (f_count * 8)) = bit
                            f_count += 1
                        Next
                        f_BLoffset += 16
                        f_EEoffset += 1
                    Next
                    f_EEprom(12) = dCurrent.Item("SerialNo") \ &H10000
                    f_EEprom(13) = HIBYTE(dCurrent.Item("SerialNo"))
                    f_EEprom(14) = LOBYTE(dCurrent.Item("SerialNo"))
                    m_ptRow = dCurrent
                    Exit For
                End If
            Next
            If Not f_found Then
                Dim rand As New Random()
                Dim f_BLoffset As Integer = 3952
                Dim f_EEoffset As Integer = 136
                Dim f_code(15) As Byte
                Dim n_row As DataRow = DataSet1.Tables("Codes").NewRow
                Dim f_count As Integer = 0
                Dim s As Integer
                n_row.Item("SerialNo") = Val(txNumber.Text)
                For i As Integer = 1 To 8
                    rand.NextBytes(f_code)
                    n_row.Item("Security Code" & Str(i)) = cv_HexFromBytes(f_code)
                    f_count = 0
                    For Each bit As Byte In f_code
                        'f_boot(f_BLoffset + f_count) = bit
                        f_EEprom(f_EEoffset - (f_count * 8)) = bit
                        f_count += 1
                    Next
                    f_BLoffset += 16
                    f_EEoffset += 1
                Next
                Dim s_num(1) As Byte
                f_EEprom(12) = Val(txNumber.Text) \ &H10000
                f_EEprom(13) = HIBYTE(Val(txNumber.Text))
                f_EEprom(14) = LOBYTE(Val(txNumber.Text))
                Try
                    DataSet1.Tables("Codes").Rows.Add(n_row)
                    s = odbcCodesAdapter.Update(DataSet1)
                Catch ex As Exception
                    MessageBox.Show(ex.Message)
                    Exit Sub
                End Try
            End If
            'arrayDump(f_EEprom, Application.StartupPath + "\eepromDump.bin")
            ' arrayDump(f_boot, Application.StartupPath + "\flashDump.bin")
            'Set the process and go CRAZY ON IT!
            'Exit Sub
            dg1.RowCount = 0
            If m_upload = False Then
                Dim Prog As New Program(f)
                Prog.m_eeprom = f_EEprom
                Prog.m_flash = f_boot
                Prog.m_firmware = f_firm
                bwgProgram.WorkerReportsProgress = True
                bwgProgram.WorkerSupportsCancellation = True
                bwgProgram.RunWorkerAsync(Prog)
                m_upload = True
                m_CurrentTest = Test_Number.Board_Program
                cbEnable1.Checked = False
            End If

            Test_CheckBoxOutput_Clear()
        End If
    End Sub
    Private Sub setBar(ByVal perCent As Integer)
        Me.pbMain.Maximum = 100
        Me.pbMain.Minimum = 0
        If (perCent <= 100) And (perCent >= 0) Then
            Me.pbMain.Value = perCent
        End If
    End Sub
    Private Sub Err_message(ByVal str_ As String)
        Me.stText.Text = str_
        If dg1.RowCount >= 2 Then
            If str_ <> dg1.Item(0, dg1.RowCount - 1).Value Then
                dg1.RowCount += 1
                dg1.Item(0, dg1.RowCount - 1).Value = str_
            End If
        Else
            dg1.RowCount += 1
            dg1.Item(0, dg1.RowCount - 1).Value = str_
        End If
    End Sub

    Private Sub Test_CheckBoxOutput_Clear()
        Me.cbLoad.Text = ""
        Me.cbLoad.Checked = False

        Me.cbLookback.Text = ""
        Me.cbLookback.Checked = False

        Me.cbProgram.Text = ""
        Me.cbProgram.Checked = False

        Me.cbTestPattern.Text = ""
        Me.cbTestPattern.Checked = False

        Me.cbLookback2.Text = ""
        Me.cbLookback2.Checked = False

        Me.cbFlash.Text = ""
        Me.cbFlash.Checked = False

    End Sub
    Private Sub Test_CheckBoxOutput_Set(ByVal value As Test_Number, ByVal status As Boolean)
        Dim item As CheckBox = Nothing
        Select Case value
            Case Test_Number.Board_Program
                item = Me.cbProgram
                Me.cbProgram.Text = "Passed"
            Case Test_Number.Consult_Loopback
                item = Me.cbLookback
            Case Test_Number.Load_BaseData
                item = Me.cbLoad
            Case Test_Number.Test_Pattern
                item = Me.cbTestPattern
            Case Test_Number.Consult_LoopBackClk
                item = Me.cbLookback2
            Case Test_Number.Flash_Test
                item = Me.cbFlash
        End Select
        If Not IsNothing(item) Then
            If status Then
                item.Text = "Passed"
                item.CheckState = CheckState.Checked
            Else
                item.Text = "Failed!"
                item.CheckState = CheckState.Indeterminate
            End If
        End If
    End Sub

    Private Sub bwgProgram_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bwgProgram.DoWork
        Dim pr As Program = CType(e.Argument, Program)
        AddHandler pr.Message, AddressOf EventProgramProgress
        AddHandler pr.Progress, AddressOf EventProgramProgress

        pr.Execute(bwgProgram, e)
    End Sub
    Private Sub bwgProgram_ProgressChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bwgProgram.ProgressChanged
        Dim state As Emergency_Args = CType(e.UserState, Emergency_Args)
        Me.setBar(state.Progress)
        Me.Err_message(state.Message)
    End Sub
    Private Sub bwgProgram_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bwgProgram.RunWorkerCompleted
        m_upload = False
        If Not IsNothing(m_ptRow) Then
            ' m_ptRow.Item("Date Programmed") = DateTime.Today
        End If
        Close_BikiRom()
    End Sub
    Private Sub EventProgramProgress( _
      ByVal sender As Object, ByVal e As Emergency_Args)

        ' A file was found. Report the progress, triggering the
        ' BackgroundWorker.ProgressChanged event:
        Dim intPercent As Integer = e.Progress
        If intPercent >= 100 Then
            intPercent = 100
        ElseIf intPercent < 0 Then
            intPercent = 0
        End If
        bwgProgram.ReportProgress(intPercent, e)
    End Sub

    Private Sub LoadBMDFileToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LoadBMDFileToolStripMenuItem.Click
        fOpen.Title = "Select .bmd File to import into database"
        fOpen.Filter = "*.bmd Bikirom REturn Codes|*.bmd"

        If fOpen.ShowDialog = Windows.Forms.DialogResult.OK Then
            Dim f_ee As New MemoryStream(arrayLoad(fOpen.FileName))
            Dim f_eeOut As New MemoryStream
            CryptFile("This IS! not a TEST moFO But This one IS", f_ee, f_eeOut, False)

            Dim f_eeProm() As Byte = f_eeOut.ToArray
            Dim f_key(7) As String
            Dim f_keyBytes(15) As Byte
            Dim f_count As Integer = 0
            Dim f_eeoffset As Integer = 136

            Dim dCurrent As DataRow
            dCurrent = DataSet1.Tables("Codes").NewRow

            For i As Integer = 1 To 8
                f_count = 0
                For s As Integer = 0 To 15
                    f_keyBytes(s) = f_eeprom(f_eeoffset - (f_count * 8))
                    f_count += 1
                Next
                f_eeoffset += 1
                dCurrent("Security Code " & i) = cv_HexFromBytes(f_keyBytes)
            Next
            dCurrent("SerialNoGen") = MAKEWORD(f_eeProm(14), f_eeProm(13))
            dCurrent("File") = fOpen.FileName.Substring(fOpen.FileName.LastIndexOf("\") + 1)

            DataSet1.Tables("Codes").Rows.Add(dCurrent)

            Dim f As Integer = Me.odbcCodesAdapter.Update(DataSet1)
        End If
    End Sub

    Private Sub cnGenCodes_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cnGenCodes.Click
        If MsgBox("Sure you want to generate mode codes?", MsgBoxStyle.OkCancel) = MsgBoxResult.Ok Then
            Dim KeyGen As New Random()

            Dim s As Integer
            Dim dCurrent As DataRow
            Dim dKey(0 To 15) As Byte
            For d As Integer = 0 To 100
                dCurrent = DataSet1.Tables("Codes").NewRow
                For i As Integer = 1 To 8
                    KeyGen.Next()
                    KeyGen.NextBytes(dKey)
                    KeyGen.Next()
                    dCurrent.Item("Security Code" & Str(i)) = cv_HexFromBytes(dKey)
                Next
                dCurrent.Item("SerialNoGen") = dCurrent.Item("SerialNo")
                Try
                    DataSet1.Tables(0).Rows.Add(dCurrent)
                    s = Me.odbcCodesAdapter.Update(DataSet1)
                Catch ex As Exception
                    MessageBox.Show(ex.Message)
                End Try
            Next
        End If
    End Sub

    Private Sub getBoardReport()
        If m_upload = False Then
            Dim f_ret As BK_return
            f_ret = BikiRom_Init()
            If f_ret = BK_return.BK_OK Then
                Err_message("Board #: " & m_BikiInfo.BoardNo)
                Err_message("OS Version: " & Hex(m_BikiInfo.OsVersion))
                Err_message("Speed: " & m_BikiInfo.Clock & "Mhz")
                If m_BikiInfo.BaseEnabled Then Err_message("Base Enabled") : cbEnable1.Checked = True Else cbEnable1.Checked = False
                If m_BikiInfo.BoostEnabled Then Err_message("Boost Enabled") : cbEnable2.Checked = True Else cbEnable2.Checked = False
            End If
        End If
        close_bikirom()
    End Sub
    Private Sub cbEnable_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbEnable8.Click, cbEnable7.Click, cbEnable6.Click, cbEnable5.Click, cbEnable4.Click, cbEnable3.Click, cbEnable2.Click, cbEnable1.Click
        Dim f_num As Integer = sender.tag
        Dim f_ret As BK_return
        If m_upload = False And txNumber.Text <> "" Then
            Dim f_return(6) As Byte
            f_ret = BikiRom_Init()
            If f_ret = BK_return.BK_OK Then
                Dim strCode As String = ""
                For Each dCurrent As DataRow In DataSet1.Tables("Codes").Rows
                    If dCurrent.Item("SerialNo") = Val(txNumber.Text) Then
                        ' Found Matching number!
                        strCode = dCurrent.Item("Security Code" & Str(f_num))
                        Exit For
                    End If
                Next
                If strCode <> "" Then
                    Dim f_frame As Comm.Comm_Frame
                    m_BikiInfo.TimeOut = 12000
                    If strCode.Length = 32 Then
                        Err_message("Trying entered unlock Code")
                        Try
                            f_frame = New Comm.Comm_Frame(Comm.Comm_Frame.BikiFrameType.ID_RUN_COMMAND, , Comm.Comm_Frame.BikiFrameAction.RUN_SEC_UNLOCKCODE, cv_BytesFromHex(strCode), Comm.Comm_Frame.BikiFrameType.ID_LAST_COMMAND_STATUS)
                            f_frame.Send(, True)
                            Err_message("Unlock Code OK!")
                        Catch exComm As Comm_Exceptions
                            Err_message(exComm.Description)
                        Catch exUsb As USB_exceptions
                            Err_message(exUsb.Description)
                        End Try
                    End If
                End If
                m_BikiInfo.reset()
            End If
            close_bikirom()
            getBoardReport()
        Else
            If txNumber.Text = "" Then : Err_message("Enter the Board No into the text box silly") : Else : Err_message("Wait for programming to finish") : End If
        End If
    End Sub

    Private Sub GetBoardInfoToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GetBoardInfoToolStripMenuItem.Click
        getBoardReport()
    End Sub

    Private Sub cmdLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdLoad.Click
        openFile.Title = "Open Bikirom File"
        openFile.InitialDirectory = Application.StartupPath & "\BikiRom Files"
        openFile.Filter = "*.bbd BikiR0M Base Data file|*.bbd"
        m_temp = Nothing
        If m_upload = False Then
            If openFile.ShowDialog = Windows.Forms.DialogResult.OK Then
                ' Try
                Dim objBase As BikiSoft.BaseData = openBaseData(openFile.FileName)
                Dim objCar As BikiSoft.CarBase = objBase.getCar
                ' Dim frmConfig As New frmCarSelection(objCar)
                '  If frmConfig.getConfig() Then
                m_upload = True
                m_CurrentTest = Test_Number.Load_BaseData
                m_newcar = objCar
                m_mapOne = m_newcar.getMap(0)
                m_mapTwo = m_newcar.getMap(1)
                m_mapThree = m_newcar.getMap(2)
                bwUpload.WorkerReportsProgress = True
                bwUpload.WorkerSupportsCancellation = True
                Dim bkUl As BikiSoft.TH_BikiRom_Up = bUploadData(BikiAction.BK_ALL)
                bwUpload.RunWorkerAsync(bkUl)
                If Not IsNothing(m_ptRow) Then
                    ' m_ptRow.Item("PreLoaded File") = GetFileName(openFile.FileName)
                    ' m_ptRow.AcceptChanges()
                End If
                'End If
                ' Catch ex As Exception

                'End Try
            End If
        End If
    End Sub
    Private Function openBaseData(ByVal sInputFile As String) As BikiSoft.BaseData
        Dim f_return As BikiSoft.BaseData = Nothing
        Try
            Dim f_encStream As New MemoryStream(arrayLoad(sInputFile))
            Dim f_memstream As New MemoryStream()
            Dim Deserializer As New BinaryFormatter

            CryptFile("Who Wants a Body Massge Right now? Or WHAT about later? Oh YE!", f_encStream, f_memstream, False)
            Dim f_outStream As New MemoryStream
            Dim f_mem2Stream As New MemoryStream(f_memstream.ToArray)
            CompressFile(f_mem2Stream, f_outStream, False)

            Dim f_newStream As New MemoryStream(f_outStream.ToArray)
            Dim f_bdata As BikiSoft.BaseData = CType(Deserializer.Deserialize(f_newStream), BikiSoft.BaseData)
            Return f_bdata
        Catch
            f_return = Nothing
        End Try
        Return f_return
    End Function
    Private Function openCarBase(ByRef Array() As Byte) As BikiSoft.CarBase
        Dim f_ncar As BikiSoft.CarBase
        Dim f_sel As frmCarSelection
        Dim Deserializer As New BinaryFormatter
        Try
            ' --------------------------- Try Opening New Encrypted AND comp BikiRom File ----------------------------------
            Dim f_encryptStream As New MemoryStream(Array)
            Dim f_decyptStream As New MemoryStream

            ' ---------------------------- Decrypt Stream and Deflate info a memory stream 
            CryptFile("I5 i7 N07 B35T t() D0 \\'4|-|7 iS ASdlhpi324_+_0=09-8)&*(&^$&^)&%$^$@#hjkN;L:kjbdiy@gbb@bkdb@ lkB", f_encryptStream, f_decyptStream, False)
            Dim f_uncomp As New MemoryStream
            Dim f_Comp As New MemoryStream(f_decyptStream.ToArray)
            CompressFile(f_Comp, f_uncomp, False)

            ' ---------------------------- Deserialise and open!
            'Dim f_memStream As New MemoryStream(f_uncomp)
            f_ncar = CType(Deserializer.Deserialize(f_uncomp), BikiSoft.CarBase)
            f_sel = New frmCarSelection(f_ncar)
            f_sel.getConfig()
            If IsNothing(f_ncar.getConfig) Then
                Err_message("Configuration Not Found..")
                If f_sel.ShowDialog() <> Windows.Forms.DialogResult.OK Then
                    Err_message("Configuration Not Selected")
                    Return Nothing
                    Exit Function
                End If
            End If

            f_uncomp.Close()
            f_decyptStream.Close()
            f_encryptStream.Close()

            f_sel = Nothing
            Return f_ncar
            Exit Function
        Catch ex As Exception
            '--------------------------------Try Opening New UN-ENC/COMP Bikirom File (DEPRESIATED)-------------------------------
            Try
                f_ncar = CType(Deserializer.Deserialize(New MemoryStream(Array)), BikiSoft.CarBase)
                f_sel = New frmCarSelection(f_ncar)
                f_sel.getConfig()
                If IsNothing(f_ncar.getConfig) Then
                    Err_message("Configuration Not Found..")
                    If f_sel.ShowDialog() <> Windows.Forms.DialogResult.OK Then
                        Err_message("Configuration Not Selected")
                        Return Nothing
                        Exit Function
                    End If
                End If
                f_sel = Nothing
                Return f_ncar
                Exit Function
            Catch
                ' --------------------------------------- Try Opening OLD BIKIROM CAR FILE AND IMPORT -----------------
                'Return openCarBaseOld(Array)
            End Try
        End Try
        Return Nothing
    End Function

    Private Function bUploadData(ByVal Action As BikiAction) As BikiSoft.TH_BikiRom_Up
        Dim d_stream() As Byte
        Dim ul As BikiSoft.TH_BikiRom_Up = Nothing
        Dim DataStream As New MemoryStream()
        Dim serializer As New BinaryFormatter
        DataStream.SetLength(65536)
        'Debug.Print("Uploading data now")
        If Action >= BikiAction.BK_MAP1 And Action <= BikiAction.BK_ALL Then

            If Action And BikiAction.BK_MAP1 Then
                If IsNothing(m_newcar.getConfig.getBikiVars.getByName("27C256")) Then
                    ul = New BikiSoft.TH_BikiRom_Up(BikiAction.BK_MAP1, g_packetSize, m_mapOne, lngHandle)
                Else
                    ul = New BikiSoft.TH_BikiRom_Up(BikiAction.BK_MAP1, g_packetSize, arrayPad(m_mapOne, True), lngHandle)
                End If
            End If

            If Action And BikiAction.BK_MAP2 Then
                If IsNothing(m_newcar.getConfig.getBikiVars.getByName("27C256")) Then
                    ul = New BikiSoft.TH_BikiRom_Up(BikiAction.BK_MAP2, g_packetSize, m_mapTwo, lngHandle)
                Else
                    ul = New BikiSoft.TH_BikiRom_Up(BikiAction.BK_MAP2, g_packetSize, arrayPad(m_mapTwo, True), lngHandle)
                End If
            End If

            If Action And BikiAction.BK_MAP3 Then
                If IsNothing(m_newcar.getConfig.getBikiVars.getByName("27C256")) Then
                    ul = New BikiSoft.TH_BikiRom_Up(BikiAction.BK_MAP3, g_packetSize, m_mapThree, lngHandle)
                Else
                    ul = New BikiSoft.TH_BikiRom_Up(BikiAction.BK_MAP3, g_packetSize, arrayPad(m_mapThree, True), lngHandle)
                End If
            End If

            If Action And BikiAction.BK_CFG Then
                Dim f_TempCar As BikiSoft.CarBase = BikiSoft.ObjectCopy(m_newcar)
                f_TempCar.setForUpload()
                serializer.Serialize(DataStream, f_TempCar)
                d_stream = DataStream.ToArray()
                ul = New BikiSoft.TH_BikiRom_Up(BikiAction.BK_CFG, g_packetSize, d_stream, lngHandle)
            End If

            If Action And BikiAction.BK_ALL Then
                Dim Allcheck(&H3FFFF) As Byte

                ' ---------------------------------------------- Copy Object and prepare to zip and compress
                Dim f_TempCar As BikiSoft.CarBase = BikiSoft.ObjectCopy(m_newcar)
                f_TempCar.setForUpload()
                Dim f_memstream As New MemoryStream
                serializer.Serialize(f_memstream, f_TempCar)

                ' ---------------------------------------------- Zip and Encrypt
                Dim f_ZipStream As New MemoryStream
                CompressFile(f_memstream, f_ZipStream, True)
                Dim f_fullstream As New MemoryStream()
                f_fullstream.SetLength(65528)
                f_fullstream.Write(f_ZipStream.ToArray, 0, f_ZipStream.Length)
                Dim f_tmstream As New MemoryStream(f_fullstream.ToArray)
                Dim f_encStream As New MemoryStream()
                CryptFile("I5 i7 N07 B35T t() D0 \\'4|-|7 iS ASdlhpi324_+_0=09-8)&*(&^$&^)&%$^$@#hjkN;L:kjbdiy@gbb@bkdb@ lkB", f_tmstream, f_encStream, True)
                d_stream = f_encStream.ToArray

                ' ---------------------------------------------- Check for EPROM and upload like crazy
                Debug.Print("bfore the check for 27c")
                If IsNothing(m_newcar.getConfig.getBikiVars.getByName("27C256")) Then

                    array_copy(m_mapOne, 0, Allcheck, 0, 65536)
                    array_copy(m_mapTwo, 0, Allcheck, 65536, 65536)
                    array_copy(m_mapThree, 0, Allcheck, 131072, 65536)

                    array_copy(cv_BytesFromHex("3040105A669123"), 0, Allcheck, 3211, 7)
                    array_copy(cv_BytesFromHex("3040105A669123"), 0, Allcheck, 3211 + &H10000, 7)
                    array_copy(cv_BytesFromHex("3040105A669123"), 0, Allcheck, 3211 + &H20000, 7)

                    Debug.Print("after the check copied ok")
                Else
                    array_copy(arrayPad(m_mapOne, True), 0, Allcheck, 0, 65536)
                    array_copy(arrayPad(m_mapTwo, True), 0, Allcheck, 65536, 65536)
                    array_copy(arrayPad(m_mapThree, True), 0, Allcheck, 131072, 65536)
                End If
                array_copy(d_stream, 0, Allcheck, &H30000, 65536)
                ul = New BikiSoft.TH_BikiRom_Up(BikiAction.BK_CFG + BikiAction.BK_MAP1 + BikiAction.BK_MAP2 + BikiAction.BK_MAP3, g_packetSize, Allcheck, lngHandle)
                Dim f_crc As New BikiSoft.libCRC32
                ul.m_CRC1 = f_crc.GetByteArrayCrc32(m_mapOne)
                ul.m_CRC2 = f_crc.GetByteArrayCrc32(m_mapTwo)
                ul.m_CRC3 = f_crc.GetByteArrayCrc32(m_mapThree)
            End If
        End If
        Return ul
    End Function
    Private Function arrayPad(ByRef array() As Byte, ByVal PadOrDePad As Boolean) As Byte()
        Dim f_return() As Byte = Nothing
        If PadOrDePad Then
            ReDim f_return(0 To (array.GetLength(0) * 2) - 1)
            For i As Integer = 0 To array.GetUpperBound(0)
                f_return(i * 2) = array(i)
                f_return((i * 2) + 1) = array(i)
            Next
        Else
            ReDim f_return(0 To (array.GetLength(0) \ 2) - 1)
            For i As Integer = 0 To UBound(f_return)
                f_return(i) = array(i * 2)
            Next
        End If
        Return f_return
    End Function
    Private Sub EventBikiProgressUp( _
      ByVal sender As Object, ByVal e As BikiSoft.Threads.BikiThread_Args)

        ' A file was found. Report the progress, triggering the
        ' BackgroundWorker.ProgressChanged event:
        Dim intPercent As Integer = e.Progress
        If intPercent >= 100 Then
            intPercent = 100
        ElseIf intPercent < 0 Then
            intPercent = 0
        End If
        bwUpload.ReportProgress(intPercent, e)
    End Sub
    Private Sub bwUpload_ProgressChanges( _
            ByVal sender As Object, _
            ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bwUpload.ProgressChanged
        Dim state As BikiSoft.Threads.BikiThread_Args = CType(e.UserState, BikiSoft.Threads.BikiThread_Args)
        Me.setBar(state.Progress)
        Err_message(state.Message)
    End Sub
    Private Sub bwUpload_RunWorkerCompleted( _
            ByVal sender As Object, _
            ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bwUpload.RunWorkerCompleted
        'On Error Resume Next
        ' Check the Error property before checking the Cancelled property:
        If e.Error IsNot Nothing Then
            Err_message(e.Error.Message)
        ElseIf e.Cancelled Then
            Err_message("Upload cancelled")
        End If
        m_upload = False
        If m_CurrentTest = Test_Number.Load_BaseData Then
            Err_message("Verifying Upload....")
            bDownloadAllVerify()
        Else
            Test_CheckBoxOutput_Set(Test_Number.Test_Pattern, True)
        End If
        'MsgBox("Please reset ECU" & Chr(13) & "turn key off and on" & Chr(13) & "wait for all relays to turn off", MsgBoxStyle.Information, "Reset ECU")
    End Sub
    Private Sub bwUpload_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bwUpload.DoWork
        Dim ul As BikiSoft.TH_BikiRom_Up = CType(e.Argument, BikiSoft.TH_BikiRom_Up)
        AddHandler ul.Progress, AddressOf EventBikiProgressUp
        AddHandler ul.Message, AddressOf EventBikiProgressUp
        ul.Execute(bwUpload, e)
    End Sub

    Private Function bDownloadData(ByVal Action As BikiAction) As BikiSoft.TH_BikiRom_Down
        Dim bkDown As BikiSoft.TH_BikiRom_Down = Nothing

        bkDown = New BikiSoft.TH_BikiRom_Down(g_packetSize, Action)
        Return bkDown
    End Function
    Private Sub bDownloadAllVerify()
        Dim bkDown As BikiSoft.TH_BikiRom_Down = bDownloadData(BikiAction.BK_ALL)
        If Not IsNothing(bkDown) And m_upload = False Then
            m_upload = True
            bwDownload.WorkerReportsProgress = True
            bwDownload.WorkerSupportsCancellation = True
            bwDownload.RunWorkerAsync(bkDown)
        End If
    End Sub
    Private Sub EventBikiProgress( _
      ByVal sender As Object, ByVal e As BikiSoft.TH_BikiRom_DownArgs)

        ' A file was found. Report the progress, triggering the
        ' BackgroundWorker.ProgressChanged event:
        Dim intPercent As Integer = e.Progress
        If intPercent >= 100 Then
            intPercent = 100
        ElseIf intPercent < 0 Then
            intPercent = 0
        End If
        bwDownload.ReportProgress(intPercent, e)
    End Sub
    Private Sub bwDownload_ProgressChanges( _
        ByVal sender As Object, _
        ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bwDownload.ProgressChanged

        Dim state As BikiSoft.TH_BikiRom_DownArgs = CType(e.UserState, BikiSoft.TH_BikiRom_DownArgs)
        Me.setBar(state.Progress)
        Err_message(state.Message)
        If Not IsNothing(state.getArray) Then
            m_temp = state.getArray
        End If
    End Sub
    Private Sub bwDownload_RunWorkerCompleted( _
        ByVal sender As Object, _
        ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bwDownload.RunWorkerCompleted
        ' Check the Error property before checking the Cancelled property:
        If e.Error IsNot Nothing Then
            Err_message(e.Error.Message)
        ElseIf e.Cancelled Then
            Err_message("Download cancelled")
        Else
        End If
        m_upload = False
        dDownloadVerify()
    End Sub
    Private Sub bwDownload_DoWork(ByVal sender As System.Object, _
    ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bwDownload.DoWork
        Dim bk As BikiSoft.TH_BikiRom_Down = CType(e.Argument, BikiSoft.TH_BikiRom_Down)
        AddHandler bk.Progress, AddressOf EventBikiProgress
        AddHandler bk.Message, AddressOf EventBikiProgress
        AddHandler bk.getArray, AddressOf EventBikiProgress

        bk.Execute(bwDownload, e)
    End Sub
    Private Sub dDownloadVerify()
        Dim fOk As Boolean = True
        If Not IsNothing(m_temp) AndAlso m_temp.Length >= &H40000 Then
            Dim d_stream(65535) As Byte
            array_copy(m_temp, &H30000, d_stream, 0, &H10000)
            Dim f_newcar As BikiSoft.CarBase = openCarBase(d_stream)

            Dim objCrc32 As New BikiSoft.libCRC32()

            If Not IsNothing(f_newcar) Then

                Dim f_one(f_newcar.DataEnd) As Byte
                Dim f_two(f_newcar.DataEnd) As Byte
                Dim f_three(f_newcar.DataEnd) As Byte
                Dim f_vOne() As Byte = Nothing
                Dim f_vTwo() As Byte = Nothing
                Dim f_vThree() As Byte = Nothing

                array_copy(m_temp, 0, f_one, 0, &H10000)
                array_copy(m_temp, &H10000, f_two, 0, &H10000)
                array_copy(m_temp, &H20000, f_three, 0, &H10000)

                If SecurityCheck(f_one) Then
                    For i As Integer = 0 To 4096
                        f_one(i) = 255
                    Next
                    If objCrc32.GetByteArrayCrc32(f_one) <> objCrc32.GetByteArrayCrc32(m_newcar.getMap(0)) Then
                        Err_message("Failed CRC on Map One")
                        fOk = False
                    End If
                Else
                    Err_message("Failed Security Bytes on Map One")
                    fOk = False
                End If
                If SecurityCheck(f_two) Then
                    For i As Integer = 0 To 4096
                        f_two(i) = 255
                    Next
                    If objCrc32.GetByteArrayCrc32(f_two) <> objCrc32.GetByteArrayCrc32(m_newcar.getMap(1)) Then
                        Err_message("Failed CRC on Map Two")
                        fOk = False
                    End If
                Else
                    Err_message("Failed Security Bytes on Map Two")
                    fOk = False
                End If
                If SecurityCheck(f_three) Then
                    For i As Integer = 0 To 4096
                        f_three(i) = 255
                    Next
                    If objCrc32.GetByteArrayCrc32(f_three) <> objCrc32.GetByteArrayCrc32(m_newcar.getMap(2)) Then
                        Err_message("Failed CRC on Map Three")
                        fOk = False
                    End If
                Else
                    Err_message("Failed Security Bytes on Map Three")
                    fOk = False
                End If
                If fOk Then
                    Err_message("CRC Verification PASSED!")
                    Err_message("Tag board with serial number, OK to ship!")
                Else
                    fOk = False
                    Err_message("CRC Verification FAILED!!")
                    Err_message("Use BikiSOFT v2 to verify")
                End If
            End If
        Else
            fOK = False
            Err_message("Download Verify Failed, data not downloaded ok (size)")
        End If
        If m_CurrentTest = Test_Number.Load_BaseData Then
            Test_CheckBoxOutput_Set(Test_Number.Load_BaseData, fOk)
        End If
    End Sub
    Private Function SecurityCheck(ByRef Array() As Byte) As Boolean
        If UBound(Array) >= 4000 Then
            Dim f_txt(6) As Byte
            array_copy(Array, 3211, f_txt, 0, 7)
            If cv_HexFromBytes(f_txt) = "3040105A669123" Then
                Return True
            Else
                Return False
            End If
        Else
            Return False
        End If
    End Function


    Private Sub cnBPupBoot_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cnBPupBoot.Click
        Dim f As BK_SPEEDS

        Select Case cbSpeed.SelectedIndex
            Case 0
                f = BK_SPEEDS.BK_8MHz
            Case 1
                f = BK_SPEEDS.BK_12MHz
            Case 2
                f = BK_SPEEDS.BK_16MHz
            Case Else
                MsgBox("Invalid speed selected")
                Exit Sub
        End Select

        Dim a_data(4095) As Byte
        Dim fnum As Integer = FreeFile()
        Dim i As Long
        CodeFile.Title = "Select Bootloader Binary to Upload"
        CodeFile.Filter = "*.bin binary|*.bin"
        CodeFile.ShowDialog()
        'Try
        For i = 0 To 4095
            a_data(i) = &HFF
        Next

        FileOpen(fnum, CodeFile.FileName, OpenMode.Binary)
        For i = 1 To LOF(fnum)
            FileGet(fnum, a_data(i - 1), i)
        Next
        FileClose(fnum)

        Dim prog As New Program(f)
        prog.m_flash = a_data
        prog.eeprom = Nothing
        prog.firmware = Nothing

        dg1.RowCount = 0
        If m_upload = False Then
            bwgProgram.WorkerReportsProgress = True
            bwgProgram.WorkerSupportsCancellation = True
            bwgProgram.RunWorkerAsync(prog)
            m_upload = True
            cbEnable1.Checked = False
        End If
    End Sub

    Private Sub cmdTestPattern_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdTestPattern.Click
        m_temp = Nothing
        If m_upload = False Then
            Dim arrPattern(&H3FFFF) As Byte

            For i As Integer = 0 To &H3FFFF - 2 Step 2
                arrPattern(i) = HIBYTE((i / 2) And &HFFFF)
                arrPattern(i + 1) = LOBYTE((i / 2) And &HFFFF)
                'arrPattern(i + 2) = &H55
                'arrPattern(i + 3) = LOBYTE(((i + 2) / 2))
            Next

            m_upload = True

            m_CurrentTest = Test_Number.Test_Pattern

            bwUpload.WorkerReportsProgress = True
            bwUpload.WorkerSupportsCancellation = True

            Dim bkUl As BikiSoft.TH_BikiRom_Up = New BikiSoft.TH_BikiRom_Up(BikiAction.BK_CFG + BikiAction.BK_MAP1 + BikiAction.BK_MAP2 + BikiAction.BK_MAP3, g_packetSize, arrPattern, lngHandle)
            bwUpload.RunWorkerAsync(bkUl)

        End If
    End Sub

    Private Sub cmdLoopTest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdLoopTest.Click, cmdLoopTest2.Click, cmdFlashTest.Click
        Dim f_frame As BikiSoft.Comm.Comm_Frame
        If BikiRom_Init(True) = BK_return.BK_OK Then
            Try
                Select Case CType(sender.tag, Int16)
                    Case 1
                        f_frame = New Comm.Comm_Frame(Comm.Comm_Frame.BikiFrameType.ID_RUN_COMMAND, , Comm.Comm_Frame.BikiFrameAction.RUN_DIAG_RXTX, Nothing, Comm.Comm_Frame.BikiFrameType.ID_LAST_COMMAND_STATUS)
                    Case 2
                        f_frame = New Comm.Comm_Frame(Comm.Comm_Frame.BikiFrameType.ID_RUN_COMMAND, , Comm.Comm_Frame.BikiFrameAction.RUN_DIAG_RXCLK, Nothing, Comm.Comm_Frame.BikiFrameType.ID_LAST_COMMAND_STATUS)
                    Case 3
                        f_frame = New Comm.Comm_Frame(Comm.Comm_Frame.BikiFrameType.ID_RUN_COMMAND, , Comm.Comm_Frame.BikiFrameAction.RUN_DIAG_FLASH, Nothing, Comm.Comm_Frame.BikiFrameType.ID_LAST_COMMAND_STATUS)
                    Case Else
                        Return
                End Select

                f_frame.Send(, True, 0)
                Select Case CType(sender.tag, Int16)
                    Case 1
                        Test_CheckBoxOutput_Set(Test_Number.Consult_Loopback, True)
                    Case 2
                        Test_CheckBoxOutput_Set(Test_Number.Consult_LoopBackClk, True)
                    Case 3
                        Test_CheckBoxOutput_Set(Test_Number.Flash_Test, True)
                End Select

                Err_message("Test Passed")
            Catch exComm As Comm_Exceptions
                Select Case CType(sender.tag, Int16)
                    Case 1
                        Test_CheckBoxOutput_Set(Test_Number.Consult_Loopback, False)
                    Case 2
                        Test_CheckBoxOutput_Set(Test_Number.Consult_LoopBackClk, False)
                    Case 3
                        Test_CheckBoxOutput_Set(Test_Number.Flash_Test, False)
                End Select
                Err_message("Test Failed")
            Catch exUsb As USB_exceptions
                Err_message(exUsb.Description)
            Finally
                close_bikirom()
            End Try
        Else
            Err_message(Err_Decode(BK_return.BK_FAILED_INIT))
        End If
    End Sub

End Class
